package com.ics.cmsadmin.modules.system.controller;

import com.ics.cmsadmin.frame.core.annotation.Authorize;
import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.enums.AuthorizeEnum;
import com.ics.cmsadmin.modules.basic.bean.PictureBean;
import com.ics.cmsadmin.modules.basic.service.PictureService;
import com.ics.cmsadmin.modules.system.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Sandwich on 2018-07-14
 */
@Api(description = "图片上传接口")
@RestController
@RequestMapping("/api/upload")
@Log4j2
public  class UploadController {

    @Autowired
    private PictureService pictureService;
    @Autowired
    private UploadService uploadService;

    @Authorize(AuthorizeEnum.IMAGE_INSERT)
    @ApiOperation(value = "改名后上传图片到阿里云存储")
    @PostMapping(value = "/renamedImage.do")
    public ApiResponse renamedImage(@RequestParam("file") MultipartFile file,@RequestParam(value = "picId", required = false) Integer picId,
                                         @RequestParam(value = "description", required = false) String description,
                                         @RequestParam(value = "picType", required = false) Integer picType, HttpServletRequest request) {
        if (file.isEmpty()) {
            log.error("Failed to upload rename image because the file is empty");
            return ApiResponse.getResponse(ApiResultEnum.PARAM_ERROR);
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            log.error("Failed to upload rename image because the file size is bigger than 10M");
            return ApiResponse.getResponse(ApiResultEnum.FILE_TOO_BIG);
        }
        Boolean isImage = verifyImage(file);
        if (!isImage){
            log.error("Failed to upload rename image because the file is not image type");
            return ApiResponse.getResponse(ApiResultEnum.FILE_FORMAT_ERR);
        }
        Map<String,Object> map = new HashMap<>();
        try {
            map = uploadService.uploadRenameImage(file);
            if (!(Boolean)map.get("result")) {
                log.error("Failed to upload rename image");
                return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
            }
            log.info("Upload rename image success");
        }catch (Exception e){
            log.error(e.getMessage());
            return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
        }
        String imageUrl = (String) map.get("data");
        PictureBean picture = savePicture(picId, description, picType, imageUrl);
        return ApiResponse.getDefaultResponse(picture);
    }

    private PictureBean savePicture(@RequestParam(value = "picId", required = false) Integer picId, @RequestParam(value = "description", required = false) String description, @RequestParam(value = "picType", required = false) Integer picType, String imageUrl) {
        PictureBean picture = PictureBean.builder()
            .description(description)
            .picType(picType)
            .picUrl(imageUrl).build();
        if (picId != null) {
            PictureBean pic = pictureService.queryById(Long.valueOf(picId));
            if (pic != null) {
                uploadService.deleteUploadedImageByUrl(pic.getPicUrl());
            }
        }
        pictureService.save(picture);
        return picture;
    }

    private Boolean verifyImage(@RequestParam("file") MultipartFile file) {
        Boolean isImage = false;
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (suffixName.toLowerCase().equals(".png") ||  suffixName.toLowerCase().equals(".jpg")
            || suffixName.toLowerCase().equals(".gif") || suffixName.toLowerCase().equals(".jpeg")
                ||suffixName.toLowerCase().equals(".ico")){
            isImage = true;
        }
        return isImage;
    }

    @Authorize(AuthorizeEnum.IMAGE_INSERT)
    @ApiOperation(value = "上传图片到阿里云存储")
    @PostMapping(value = "/image.do")
    public ApiResponse image(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value = "picId", required = false) Integer picId,
                                   @RequestParam(value = "description", required = false) String description,
                                   @RequestParam(value = "picType", required = false) Integer picType,
                                   HttpServletRequest request) {
        if (file.isEmpty()) {
            return ApiResponse.getResponse(ApiResultEnum.PARAM_ERROR);
        }
        if (file.getSize() > 1024 * 500) {
            return ApiResponse.getResponse(ApiResultEnum.FILE_TOO_BIG);
        }
        Boolean isImage = verifyImage(file);
        if (!isImage){
            return ApiResponse.getResponse(ApiResultEnum.FILE_FORMAT_ERR);
        }
        Map<String,Object> map = new HashMap<>();
        try {
            map = uploadService.uploadImage(file);
            if (!(Boolean)map.get("result")) {
                return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
        }
        Map res = new HashMap();
        String imageUrl = (String) map.get("data");
        res.put("imageUrl", imageUrl);
        savePicture(picId, description, picType, imageUrl);
        return ApiResponse.getDefaultResponse(res);
    }

    @Authorize(AuthorizeEnum.FILE_INSERT)
    @ApiOperation(value = "上传重命名后的文件到阿里云存储")
    @PostMapping(value = "/renamedFile.do")
    public ApiResponse renamedFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return ApiResponse.getResponse(ApiResultEnum.PARAM_ERROR);
        }
        if (file.getSize() > 1024 * 500) {
            return ApiResponse.getResponse(ApiResultEnum.FILE_TOO_BIG);
        }
        Map<String,Object> map = new HashMap<>();
        try {
            map = uploadService.uploadRenameFile(file);
            if (!(Boolean) map.get("result")) {
                return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
        }
        Map res = new HashMap();
        res.put("imageUrl", map.get("data"));
        return ApiResponse.getDefaultResponse(res);
    }

    @Authorize(AuthorizeEnum.FILE_INSERT)
    @ApiOperation(value = "上传文件到阿里云存储")
    @PostMapping(value = "/file.do")
    public ApiResponse file(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return ApiResponse.getResponse(ApiResultEnum.PARAM_ERROR);
        }
        // file.getSize 返回的size单位是byte，之前是500K，现在改成500M
        if (file.getSize() > 1024 * 1024 * 500) {
            return ApiResponse.getResponse(ApiResultEnum.FILE_TOO_BIG);
        }
        Map<String,Object> map = new HashMap<>();
        try {
            map = uploadService.uploadFile(file);
            if (!(Boolean)map.get("result")) {
                return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ApiResponse.getResponse(ApiResultEnum.FAILURE_REDIRECT);
        }
        Map res = new HashMap();
        res.put("imageUrl", map.get("data"));
        return ApiResponse.getDefaultResponse(res);
    }

}
